import { defineStore } from "pinia";
import {
  type cacheType,
  store,
  debounce,
  ascending,
  getKeyList,
  filterTree,
  constantMenus,
  filterNoPermissionTree,
  formatFlatteningRoutes,
  cloneDeep
} from "../utils";
import { useMultiTagsStoreHook } from "./multiTags";

function mergeMenuTrees(staticMenus: any[], dynamicMenus: any[]) {
  const dedupeLevel = (entries: any[]): any[] => {
    const map = new Map<any, any>();

    entries.forEach((entry, index) => {
      const current = cloneDeep(entry);
      if (current?.children?.length) {
        current.children = dedupeLevel(current.children);
      }

      const key =
        current?.path ||
        current?.name ||
        current?.redirect ||
        current?.meta?.title ||
        Symbol(`menu-${index}`);

      const existing = map.get(key);
      if (!existing) {
        map.set(key, current);
        return;
      }

      const preferCurrent =
        current?.meta?.backstage && !existing?.meta?.backstage;
      const preferExisting =
        existing?.meta?.backstage && !current?.meta?.backstage;

      const combinedChildren = [
        ...(existing?.children ?? []),
        ...(current?.children ?? [])
      ];
      const mergedChildren = combinedChildren.length
        ? dedupeLevel(combinedChildren)
        : [];

      if (preferCurrent) {
        current.children = mergedChildren.length
          ? mergedChildren
          : (existing?.children ?? current.children);
        map.set(key, current);
      } else {
        existing.meta = Object.assign(
          {},
          existing.meta ?? {},
          current.meta ?? {}
        );
        existing.children = mergedChildren.length
          ? mergedChildren
          : (existing.children ?? current.children);
        if (!preferExisting && current?.meta?.backstage) {
          existing.meta.backstage = true;
        }
        map.set(key, existing);
      }
    });

    return Array.from(map.values());
  };

  const initial = [
    ...cloneDeep(staticMenus ?? []),
    ...cloneDeep(dynamicMenus ?? [])
  ];

  return dedupeLevel(initial);
}

export const usePermissionStore = defineStore("pure-permission", {
  state: () => ({
    // 静态路由生成的菜单
    constantMenus,
    // 整体路由生成的菜单（静态、动态）
    wholeMenus: [],
    // 整体路由（一维数组格式）
    flatteningRoutes: [],
    // 缓存页面keepAlive
    cachePageList: []
  }),
  actions: {
    /** 组装整体路由生成的菜单 */
    handleWholeMenus(routes: any[]) {
      const mergedMenus = mergeMenuTrees(this.constantMenus, routes);
      const orderedMenus = ascending(cloneDeep(mergedMenus));
      const visibleMenus = filterTree(orderedMenus);
      this.wholeMenus = filterNoPermissionTree(visibleMenus);
      this.flatteningRoutes = formatFlatteningRoutes(
        cloneDeep(mergedMenus) as any
      );
    },
    cacheOperate({ mode, name }: cacheType) {
      const delIndex = this.cachePageList.findIndex(v => v === name);
      switch (mode) {
        case "refresh":
          this.cachePageList = this.cachePageList.filter(v => v !== name);
          break;
        case "add":
          this.cachePageList.push(name);
          break;
        case "delete":
          delIndex !== -1 && this.cachePageList.splice(delIndex, 1);
          break;
      }
      /** 监听缓存页面是否存在于标签页，不存在则删除 */
      debounce(() => {
        let cacheLength = this.cachePageList.length;
        const nameList = getKeyList(useMultiTagsStoreHook().multiTags, "name");
        while (cacheLength > 0) {
          nameList.findIndex(v => v === this.cachePageList[cacheLength - 1]) ===
            -1 &&
            this.cachePageList.splice(
              this.cachePageList.indexOf(this.cachePageList[cacheLength - 1]),
              1
            );
          cacheLength--;
        }
      })();
    },
    /** 清空缓存页面 */
    clearAllCachePage() {
      this.wholeMenus = [];
      this.cachePageList = [];
    }
  }
});

export function usePermissionStoreHook() {
  return usePermissionStore(store);
}
